package com.example.demo.common;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
@CrossOrigin
@ControllerAdvice
@Slf4j
public class ExceptionsHandler {

    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Map<String,Object> handleException(Exception ex) {
        if (ex instanceof BusinessException) {
            log.warn(ex.getMessage(), ex);
            BusinessException businessException = (BusinessException) ex;
            //return ExceptionResponse.create(businessException.getState(), businessException.getMessage());
            Map<String,Object> result = new HashMap<>();
            result.put("state",businessException.getState());
            result.put("msg",businessException.getMessage());
            return result;
        } else {
            log.error(ex.getMessage(), ex);
            //return ExceptionResponse.create(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage());
            Map<String,Object> result = new HashMap<>();
            result.put("state",HttpStatus.INTERNAL_SERVER_ERROR.value());
            result.put("msg",ex.getMessage());
            return result;
        }
    }
}